package com.itcoon.cloud.framework.security.filter;

import com.itcoon.cloud.framework.security.ex.SecurityResponseEnum;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckVerifyCodeFilter extends GenericFilterBean {

	private RequestMatcher requestMatcher;

	private final AuthenticationFailureHandler failureHandler;

	public CheckVerifyCodeFilter(AuthenticationFailureHandler failureHandler) {
		this.failureHandler = failureHandler;
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		if (HttpMethod.POST.name().equals(request.getMethod()) && requestMatcher.matches(request)) {
			String requestCaptcha = request.getParameter("code");
			String genCaptcha = (String) request.getSession().getAttribute("index_code");
			if (StringUtils.isEmpty(requestCaptcha)) {
				failureHandler.onAuthenticationFailure(request, response, SecurityResponseEnum.BAD_CAPTCHA.newException());
				return;
			}
			if (!genCaptcha.toLowerCase().replaceAll(" ", "").equals(requestCaptcha.toLowerCase())) {
				failureHandler.onAuthenticationFailure(request, response, SecurityResponseEnum.BAD_CAPTCHA.newException());
				return;
			}
		}
		filterChain.doFilter(request, response);
	}

	public RequestMatcher getRequestMatcher() {
		return requestMatcher;
	}

	public void setRequestMatcher(RequestMatcher requestMatcher) {
		this.requestMatcher = requestMatcher;
	}

	public AuthenticationFailureHandler getFailureHandler() {
		return failureHandler;
	}

}
